const path = require('path');
const express = require('express');
const app = express();
const { log } = require('./log-utils');

const startServer = (port, scripts) => {
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));

  // 定义处理请求的路由  
  app.all('/:keyword', async (req, res) => {
    log('info', `Received request: ${req.url}`);

    const keyword = req.params.keyword;
    const scriptConfig = scripts.find(item => item.keyword === keyword);
    if (!scriptConfig) {
      log('warn', `No script found for keyword: ${keyword}`);
      return res.status(404).send('Not Found');
    }

    const scriptPath = path.join(__dirname, '..', scriptConfig.path)
    log('info', `Executing script: ${scriptPath}`);

    try {
      const module = await import(scriptPath);
      const result = await module.default(scriptConfig.params);
      log('info', `Response: ${result}`);
      res.send(result);
    } catch (error) {
      const errorMsg = `Error executing script ${scriptPath}: ${error}`;
      log('error', errorMsg);
      return res.status(500).send(`Internal Server Error: ${error}`);
    }
  });

  // 当找不到对应的路由时，返回404  
  app.use((req, res) => {
    log('warn', `Unhandled request: ${req.url}`);
    res.status(404).send('Not Found');
  });

  app.listen(port, () => {
    log('info', `Server started on port ${port}`);
  });
};

module.exports = {
  start: startServer
};